/*
 * Includes
 */ 
#include <x32.h>
#include <ucos.h>

/*
 * Global Definitions
 */ 
#define PRIORITY 10
#define BTN3 0x08
#define BTN2 0x04
#define BTN1 0x02
#define BTN0 0x01

/*
 * Global Variables
 */
int throttle = 0;
int stack[1024];

void isr_buttons() {													// Button interupt service
	OSIntEnter();														// Stops OS temporarily to do context switching									
	if 		( peripherals[ PERIPHERAL_BUTTONS ] == BTN3 ) exit();  		// Reset button, left most on board.
	else if ( peripherals[ PERIPHERAL_BUTTONS ] == BTN0 ) throttle++;	// Increase button, right most on board.
	else if ( peripherals[ PERIPHERAL_BUTTONS ] == BTN1 ) throttle--;	// Deacrease button, right middle button on board.
	OSIntExit();														// Restore OS context switching
}

void per_task(void *data) {
	while(TRUE) {
		peripherals[PERIPHERAL_DISPLAY] 	= throttle;					// Display the throttle on the SSD
		peripherals[PERIPHERAL_DPC1_WIDTH] 	= throttle;					// Update the PWM pulse width
		OSTimeDly(1); 													// 20ms; Delay the system for one timeslice
	}
}

void main() {
	// Configure the Button ISR 
	SET_INTERRUPT_VECTOR	(INTERRUPT_BUTTONS, isr_buttons);
	SET_INTERRUPT_PRIORITY	(INTERRUPT_BUTTONS, 5);
	ENABLE_INTERRUPT		(INTERRUPT_BUTTONS);
	
	peripherals[PERIPHERAL_DPC1_PERIOD] = 1024;

	OSInit();															// Init the OS
	OSTaskCreate(per_task, (void *)0, (void *)stack, PRIORITY);			// Create per_task, with priority 10
	OSStart(); 															// Also enables the global interrupts
}
